﻿using DevExpress.XtraBars.Ribbon;
using SMART_VIET_V01.Lib;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SMART_VIET_V01
{
    public partial class frm_quanlyTuongTac : Form
    {
        SQL_Functions sql;
        public frm_quanlyTuongTac()
        {
            sql = new SQL_Functions();
            InitializeComponent();
            getlistImg();
            trView.ImageList = imgListTrView;
            loadTreeView();
            addAllListGalary();
            addGallaryDaGan();
        }
        #region Add Tree View
        public TreeNode addNode(string _name, string _caption, int _lv, TreeNode _beforNode = null)
        {

            TreeNode trNode = new TreeNode(_caption);
            trNode.Name = _name;
            trNode.ImageIndex = _lv;

            if (_beforNode != null) { _beforNode.Nodes.Add(trNode); return _beforNode; }
            else return trNode;
        }

        public void loadTreeView()
        {
            trView.SelectedImageIndex = 3;
            trView.Nodes.Clear();
            string query = "SELECT mh.stt as mhID, mh.ten_monhoc as mhTen, ml.stt as mlID,ml.ten_nhombaigiang as mlTen, bg.stt as bgID,bg.ten_baigiang as bgTen  FROM tblMonHoc mh LEFT JOIN (tbl_NhomBaiGiang ml LEFT JOIN tblBaiGiang bg ON ml.stt = bg.nhombaigiang_id)  ON mh.stt = ml.monhoc_id ";
            DataTable dt = sql.returnDB(query);
            if (dt != null)
            {
                int count = dt.Rows.Count;
                Console.WriteLine(count.ToString());
                TreeNode trNodeLv0 = null;
                TreeNode trNodeLv1 = null;
                for (int i = 0; i < count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    if (i == 0) { trNodeLv0 = addNode(dr["mhID"].ToString(), dr["mhTen"].ToString(), 0); trView.Nodes.Add(trNodeLv0); }
                    else
                    {
                        if (trNodeLv0.Name.ToString() != dr["mhID"].ToString()) { trNodeLv0 = addNode(dr["mhID"].ToString(), dr["mhTen"].ToString(), 0); trView.Nodes.Add(trNodeLv0); }
                    }
                    if (!string.IsNullOrEmpty(dr["mlID"].ToString()))
                    {
                        if (trNodeLv1 == null)
                        {
                            trNodeLv1 = addNode(dr["mlID"].ToString(), dr["mlTen"].ToString(), 1);
                            trNodeLv0.Nodes.Add(trNodeLv1);

                        }
                        else if (trNodeLv1.Name.ToString() != dt.Rows[i]["mlID"].ToString())
                        {
                            trNodeLv1 = addNode(dr["mlID"].ToString(), dr["mlTen"].ToString(), 1);
                            trNodeLv0.Nodes.Add(trNodeLv1);
                        }
                    }
                    if (!string.IsNullOrEmpty(dr["bgID"].ToString())) trNodeLv1.Nodes.Add(addNode(dr["bgID"].ToString(), dr["bgTen"].ToString(), 2));
                }
            }

        }
        public void getlistImg()
        {
            Image img = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv0;
            Image img2 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv1;
            Image img3 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv2;
            Image img4 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_selected;
            imgListTrView.Images.AddRange(new Image[] { img, img2, img3, img4 });
        }
        #endregion

        private void trView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode trNode = trView.SelectedNode;
            if (trNode != null)
            {
                if (trNode.Level == 0)
                {
                    string query = "SELECT * FROM tblTuongTacLib ttl WHERE ttl.monhoc_id = " + trNode.Name.ToString();
                    DataTable dt = sql.returnDB(query);
                    addListGallary(trNode, dt);
                }
            }
            else { addAllListGalary(); }
            addGallaryDaGan(trNode);

        }

        public void addListGallary(TreeNode trNode, DataTable dt)
        {
            addGallary(gl01, trNode, dt);
            addGallary(gl02, trNode, dt);
            addGallary(gl03, trNode, dt);

        }
        public void addAllListGalary()
        {
            string query = "SELECT * FROM tblTuongTacLib ttl";
            DataTable dt = sql.returnDB(query);
            addAllGallary(gl01, dt);
            addAllGallary(gl02, dt);
            addAllGallary(gl03, dt);
        }


        public void addGallary(GalleryControl gc, TreeNode trNode, DataTable dt = null)
        {
            gc.Gallery.Groups.Clear();
            if (dt != null)
            {
                Image img = null;
                GalleryItemGroup galleryItemGroup = new GalleryItemGroup();
                galleryItemGroup.Caption = trNode.Text.ToString();
                galleryItemGroup.Tag = trNode.Name.ToString();
                gc.Gallery.Groups.Add(galleryItemGroup);
                switch (gc.Name)
                {
                    case "gl01":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_flash;
                        break;
                    case "gl02":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_exe;
                        break;
                    case "gl03":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                        break;
                    default:
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                        break;
                }
                int count = dt.Rows.Count;
                string gcLoai = gc.Name.Substring(3).ToString();
                for (int i = 0; i < count; i++)
                {
                    GalleryItem gle = new GalleryItem();
                    gle.Caption = dt.Rows[i]["ten_tuongtac"].ToString();
                    gle.Tag = dt.Rows[i]["stt"].ToString();
                    gle.Image = img;
                    string loadTT = dt.Rows[i]["loaituongtac_id"].ToString();
                    if (loadTT == gcLoai) { gc.Gallery.Groups[0].Items.Add(gle); }
                }
            }
        }

        public void addAllGallary(GalleryControl gc, DataTable dt = null)
        {
            gc.Gallery.Groups.Clear();
            int count = trView.Nodes.Count;
            if (dt != null)
            {
                Image img = null;


                switch (gc.Name)
                {
                    case "gl01":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_flash;
                        break;
                    case "gl02":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_exe;
                        break;
                    case "gl03":
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                        break;
                    default:
                        img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                        break;
                }
                foreach (TreeNode node in trView.Nodes)
                {
                    GalleryItemGroup galleryItemGroup = new GalleryItemGroup();
                    galleryItemGroup.Caption = node.Text.ToString();
                    galleryItemGroup.Tag = node.Name.ToString();


                    int coDT = dt.Rows.Count;
                    string gcLoai = gc.Name.Substring(3).ToString();
                    for (int i = 0; i < coDT; i++)
                    {
                        GalleryItem gle = new GalleryItem();
                        gle.Caption = dt.Rows[i]["ten_tuongtac"].ToString();
                        gle.Tag = dt.Rows[i]["stt"].ToString();
                        gle.Image = img;
                        string loadTT = dt.Rows[i]["loaituongtac_id"].ToString();
                        if (loadTT == gcLoai && dt.Rows[i]["monhoc_id"].ToString() == node.Name.ToString())
                        {
                            galleryItemGroup.Items.Add(gle);
                            //gc.Gallery.Groups[0].Items.Add(gle);
                        }
                    }
                    gc.Gallery.Groups.Add(galleryItemGroup);
                }
            }
        }

        public void addGallaryDaGan(TreeNode node = null)
        {
            gl04.Gallery.Groups.Clear();
            string query = "SELECT ttg.baigiang_id AS bgID,bg.ten_baigiang AS bgTen,bg.nhombaigiang_id AS grID,grg.ten_nhombaigiang AS grTen,ttg.tuongtac_id AS ttID," +
                                         "ttb.ten_tuongtac AS ttTen,ttb.monhoc_id AS mhID,mh.ten_monhoc AS mhTen,ttb.loaituongtac_id AS loaiTT " +
                                         " FROM tlbTuongTacDaGan ttg LEFT JOIN (tblBaiGiang bg LEFT JOIN tbl_NhomBaiGiang grg ON bg.nhombaigiang_id = grg.stt) ON ttg.baigiang_id = bg.stt LEFT JOIN (tblTuongTacLib ttb LEFT JOIN tblMonHoc mh ON ttb.monhoc_id = mh.stt) ON ttg.tuongtac_id = ttb.stt ";
            if (node != null)
            {
                string id = node.Name.ToString();
                if (node.Level == 0) query = query + " WHERE ttb.monhoc_id = " + id;
                else if (node.Level == 1) query = query + " WHERE bg.nhombaigiang_id = " + id;
                else if (node.Level == 2) query = query + " WHERE ttg.baigiang_id = " + id;
            }
            DataTable dt = sql.returnDB(query);
            if (dt != null)
            {
                int count = dt.Rows.Count;
                string bgID = null;
                for (int i = 0; i < count; i++)
                {
                    if (i == 0)
                    {
                        bgID = dt.Rows[i]["bgID"].ToString();
                        GalleryItemGroup galleryItemGroup = new GalleryItemGroup();
                        galleryItemGroup.Caption = dt.Rows[i]["bgTen"].ToString();
                        galleryItemGroup.Tag = bgID;
                        gl04.Gallery.Groups.Add(galleryItemGroup);
                    }
                    else
                    {
                        if (dt.Rows[i]["bgID"].ToString() != bgID)
                        {
                            bgID = dt.Rows[i]["bgID"].ToString();
                            GalleryItemGroup galleryItemGroup = new GalleryItemGroup();
                            galleryItemGroup.Caption = dt.Rows[i]["bgTen"].ToString();
                            galleryItemGroup.Tag = bgID;
                            gl04.Gallery.Groups.Add(galleryItemGroup);
                        }
                    }
                }
                for (int y = 0; y < gl04.Gallery.Groups.Count; y++)
                {
                    for (int i = 0; i < count; i++)
                    {
                        if (gl04.Gallery.Groups[y].Tag.ToString() == dt.Rows[i]["bgID"].ToString())
                        {
                            GalleryItem gle = new GalleryItem();
                            gle.Caption = dt.Rows[i]["ttTen"].ToString();
                            gle.Tag = dt.Rows[i]["ttID"].ToString();
                            gle.Image = imgFile(dt.Rows[i]["loaiTT"].ToString());
                            gl04.Gallery.Groups[y].Items.Add(gle);
                        }
                    }
                }
            }


        }
        public Image imgFile(string text)
        {
            Image img = null;
            switch (text)
            {
                case "1":
                    img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_flash;
                    break;
                case "2":
                    img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_exe;
                    break;
                case "3":
                    img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                    break;
                default:
                    img = global::SMART_VIET_V01.Properties.Resources.quanlyTuongTac_fileOther;
                    break;
            }
            return img;
        }
        private void btnAddImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TreeNode trNode = trView.SelectedNode;
            if (trNode != null)
            {
                //Console.WriteLine(trView.SelectedNode.Parent.Parent.Text);
                openFileDialog1.Filter = "Flash Files (*.swf)|*.swf|" +
                                         "Exe Files (*.exe)|*.exe|" +
                                         "All Type |*.*";
                openFileDialog1.FileName = "";
                openFileDialog1.Title = "Thêm tương tác";
                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    string id = trNode.Name.ToString();
                    if (trNode.Level == 1) id = trNode.Parent.Name.ToString();
                    else if (trNode.Level == 2) id = trNode.Parent.Name.ToString();
                    foreach (string file in openFileDialog1.FileNames)
                    {
                        FileInfo fileInfor = new FileInfo(file);
                        string fileName = fileInfor.Name;
                        string[] strings = file.Split('.');
                        string duoi = strings[strings.Length - 1].ToString().ToLower();
                        if (duoi.Equals("swf")) duoi = "1";
                        else if (duoi.Equals("exe")) duoi = "2";
                        else duoi = "3";
                        Hashtable myMedia = new Hashtable();
                        myMedia["ten_tuongtac"] = fileName;
                        myMedia["monhoc_id"] = id;
                        myMedia["loaituongtac_id"] = duoi;
                        sql.insertMedia(myMedia, "tblTuongTacLib", "tuongtac", file);
                    }
                    trView_AfterSelect(null, null);
                }
            }
            else MessageBox.Show("Vui lòng chọn thư viện cần lưu tương tác");
        }

        private void trView_MouseDown(object sender, MouseEventArgs e)
        {
            if (trView.HitTest(e.Location).Node == null) { trView.SelectedNode = null; addAllListGalary(); }
        }

        private void gl01_Gallery_ItemClick(object sender, GalleryItemClickEventArgs e)
        {
            if (e.Item.Checked) e.Item.Checked = false;
            else e.Item.Checked = true;
        }

        private void btnDelVideo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string test = "Bạn muốn xóa những tương tác đã chọn?";
            deleteItemGallary(test);
        }
        private void btnDelImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TabPage tbTemp = tabControl.SelectedTab;
            GalleryControl gc = (GalleryControl)tbTemp.Controls[0];
            for (int i = 0; i < gc.Gallery.Groups.Count; i++)
            {
                foreach (GalleryItem item in gc.Gallery.Groups[i].Items)
                {
                    item.Checked = true;
                }
            }
            deleteItemGallary("Bạn muốn xóa toàn bộ tương tác?");
        }
        public void deleteItemGallary(string text)
        {
            TabPage tbTemp = tabControl.SelectedTab;
            GalleryControl gc = (GalleryControl)tbTemp.Controls[0];
            List<GalleryItem> items = gc.Gallery.GetCheckedItems();
            if (items.Count > 0)
            {
                DialogResult res = MessageBox.Show(text, "Xác nhận",
                                                             MessageBoxButtons.YesNo,
                                                             MessageBoxIcon.Question,
                                                             MessageBoxDefaultButton.Button2);
                if (res == DialogResult.Yes)
                {
                    string query = "DELETE FROM tblTuongTacLib WHERE stt = @sttID";
                    string queryDel = "DELETE FROM tlbTuongTacDaGan WHERE tuongtac_id = @sttID";
                    foreach (GalleryItem item in items)
                    {
                        string idbg = item.GalleryGroup.Tag.ToString();
                        string queryDelTuongTac = "DELETE FROM tlbTuongTacDaGan WHERE baigiang_id = " + idbg + " AND tuongtac_id = @sttID";
                        if (gc.Name == "gl04") sql.updateDK(queryDelTuongTac, "@sttID", item.Tag.ToString());
                        else
                        {

                            string queryChk = "SELECT ttg.baigiang_id AS bgID,bg.ten_baigiang AS bgTen,bg.nhombaigiang_id AS grID,grg.ten_nhombaigiang AS grTen,ttg.tuongtac_id AS ttID," +
                                         "ttb.ten_tuongtac AS ttTen,ttb.monhoc_id AS mhID,mh.ten_monhoc AS mhTen,ttb.loaituongtac_id AS loaiTT " +
                                         " FROM tlbTuongTacDaGan ttg LEFT JOIN (tblBaiGiang bg LEFT JOIN tbl_NhomBaiGiang grg ON bg.nhombaigiang_id = grg.stt) ON ttg.baigiang_id = bg.stt LEFT JOIN (tblTuongTacLib ttb LEFT JOIN tblMonHoc mh ON ttb.monhoc_id = mh.stt) ON ttg.tuongtac_id = ttb.stt ";
                            queryChk = queryChk + " WHERE ttb.stt = " + item.Tag.ToString();
                            DataTable dtChk = sql.returnDB(queryChk);
                            if (dtChk != null)
                            {

                                DialogResult resChk = MessageBox.Show("Tương tác " + item.Caption.ToString() + " hiện đang được gán cho các bài giảng \n Vui lòng gỡ tương tác ra khỏi các bản giảng hoặc Bạn muốn xóa tương tác này ?", "Xác nhận",
                                                             MessageBoxButtons.YesNo,
                                                             MessageBoxIcon.Question,
                                                             MessageBoxDefaultButton.Button2);
                                if (resChk == DialogResult.Yes)
                                {
                                    sql.updateDK(queryDel, "@sttID", item.Tag.ToString());
                                    sql.updateDK(query, "@sttID", item.Tag.ToString());
                                }
                            }
                            else sql.updateDK(query, "@sttID", item.Tag.ToString());
                        }
                    }
                    trView_AfterSelect(null, null);
                }
            }
            else MessageBox.Show("Vui lòng chọn file cần xóa!");
        }
        string fileName;
        private void galleryControlGallery1_ItemDoubleClick(object sender, GalleryItemClickEventArgs e)
        {
            //if (!string.IsNullOrEmpty(fileName)) { if (File.Exists(fileName)) File.Delete(fileName); }
            //string id = e.Item.Tag.ToString();
            //string query = "SELECT * FROM tblTuongTacLib WHERE stt = " + id;
            //DataTable dt = sql.returnDB(query);
            //if (dt != null)
            //{
            //    fileName = dt.Rows[0]["ten_tuongtac"].ToString();
            //    string fileNameSave = fileName;
            //    byte[] bytes = (byte[])dt.Rows[0]["tuongtac"];
            //    using (MemoryStream stream = new MemoryStream(bytes))
            //    {
            //        FileStream outStream = File.OpenWrite(fileNameSave);
            //        stream.WriteTo(outStream);
            //        Process.Start(fileNameSave);
            //    }
               
            //}
           
        }
    }
}
